package cn.huiyunche.driver.service.impl;

import cn.huiyunche.base.service.constant.TmsUrlConstant;
import cn.huiyunche.base.service.enums.DWaybillStatusEnum;
import cn.huiyunche.base.service.enums.DWaybillStatusTypeEnum;
import cn.huiyunche.base.service.enums.TmsUrlTypeEnum;
import cn.huiyunche.base.service.enums.UserTypeEnum;
import cn.huiyunche.base.service.interfaces.DUserExtService;
import cn.huiyunche.base.service.interfaces.DWaybillStatusHistoryService;
import cn.huiyunche.base.service.interfaces.TmsQueueService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.mappers.DWaybillMapper;
import cn.huiyunche.base.service.mappers.TmsOrderCallHistoryMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.utils.HttpRequestUtil;
import cn.huiyunche.base.service.vo.DWaybillErrorMsgVo;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.driver.service.DWaybillErrorMsgService;
import cn.huiyunche.driver.service.TmsCustomerService;
import cn.huiyunche.driver.service.TmsOrderHandleMsgService;
import cn.huiyunche.driver.service.TmsUpdateOrdersService;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 查询TMS信息关联人送司机与订单
 *
 * @author ligl [Tuffy]
 */
@Service
public class TmsUpdateOrdersServiceImpl implements TmsUpdateOrdersService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TmsUpdateOrdersServiceImpl.class);

    @Autowired
    private DWaybillMapper dWaybillMapper = null;

    @Autowired
    private TmsQueueService tmsQueueService;


    @Autowired
    private TmsCustomerService tmsCustomerService = null;

    @Autowired
    private UserService userService = null;

    @Autowired
    private DUserExtService dUserExtService = null;

    @Autowired
    private DWaybillStatusHistoryService dWaybillStatusHistoryService;

    @Autowired
    private DWaybillErrorMsgService dWaybillErrorMsgService;

    @Autowired
    private TmsOrderHandleMsgService tmsOrderHandleMsgService;

    @Autowired
    private TmsOrderCallHistoryMapper tmsOrderCallHistoryMapper;

    private DWaybillMapper getdWaybillMapper() {
        return this.dWaybillMapper;
    }

    private UserService getUserService() {
        return this.userService;
    }

    private DUserExtService getDUserExtService() {
        return this.dUserExtService;
    }

    @Override
    public void start() {
        this.cancelAssign();
    }


    /**
     * 取消TMS订单
     */
    public void cancelAssign() {
        String messageCode = "100";
        String message = "";
        Boolean isHandle = false;
        DWaybillErrorMsgVo errorMsgVo = new DWaybillErrorMsgVo();
        errorMsgVo.setErrCode("-1");
        errorMsgVo.setIsHandle(false);
        final String url = TmsUrlConstant.PULL_ORDER_HISTORY;
        Map<String, Object> resultMap = dWaybillErrorMsgService.listByCondition(null, errorMsgVo);
        LOGGER.info("===dWaybillErrorMsgService.listByCondition==={}", errorMsgVo.getErrCode(), errorMsgVo.getIsHandle());

        List<DWaybillErrorMsgVo> errorMsgVosList = (List<DWaybillErrorMsgVo>) resultMap.get("waybillError");

        if (null == errorMsgVosList || errorMsgVosList.size() <= 0) {
            LOGGER.info("================错误日志中已无可以待处理订单===============");
            return;
        }

        for (DWaybillErrorMsgVo vo : errorMsgVosList) {
            Map<String, Object> paramsMap = new HashedMap<>();
            DUserExt dUserExt = null;
            if (StringUtils.isNotBlank(vo.getPhone())) {
                DUserExtExample dUserExtExample = new DUserExtExample();
                dUserExtExample.createCriteria().andPhoneEqualTo(vo.getPhone());
                List<DUserExt> list = dUserExtService.selectByExample(dUserExtExample);
                if (list.size() != 1) {
                    throw new BusinessException("没有找到用户对应的信息");
                }
                dUserExt = list.get(0);
            }
            paramsMap.put("orderilineid", vo.getOrderLineId());
            paramsMap.put("vccard", dUserExt.getIdNo());
            Map<String, Object> urlResultMap = this.urlCall(url, paramsMap, 60000); //调取DTI获取TMS订单状态
            messageCode = (String) urlResultMap.get("mssagecode");
            message = (String) urlResultMap.get("mssagecode");
            LOGGER.info("===查询tms订单状态==={}", messageCode, message);

            int handleTimes = vo.getHandleTimes() + 1;//查询次数增加一次
            if ("200".equals(messageCode)) {
                DWaybillExample dWaybillExample = new DWaybillExample();
                dWaybillExample.createCriteria().andOrderCodeEqualTo(vo.getOrderCode());
                List<DWaybill> waybillList = getdWaybillMapper().selectByExample(dWaybillExample);
                if (waybillList.size() > 0 && waybillList != null) {
                    LOGGER.info("==tmsCustomerService.cancelTMSbyIDCard=={}", waybillList.get(0));
                    Result<String> result = tmsCustomerService.cancelTMSbyIDCard(waybillList.get(0)); //调取DTI取消TMS订单关联
                    if (result != null) {
                        isHandle = result.isSuccess();//判断是否需要将订单置为不再查询（true:不再查询；false：查询）
                    }
                }
            } else if ("300".equals(messageCode)) {
                isHandle = true;//判断是否需要将订单置为不再查询
            }
            dWaybillErrorMsgService.modifyisHandle(isHandle, vo.getId(), handleTimes);//修改错误日志的状态，将已修改过的日志置为不再查询
            LOGGER.info("===dWaybillErrorMsgService.modifyisHandle==={}", isHandle, vo.getId(), handleTimes);
            //记录每次查询增加日志到错误日志维护表
            TmsOrderHandleMsg handleMsg = new TmsOrderHandleMsg();
            handleMsg.setErrCode(messageCode);
            handleMsg.setErrMsg(message);
            handleMsg.setWaybillErrId(vo.getId());
            tmsOrderHandleMsgService.add(handleMsg);//添加查询运单派送日志
            LOGGER.info("===dWaybillErrorMsgService.modifyisHandle==={}", handleMsg);
        }
    }


    /**
     * 查询TMS信息后关联人送订单
     */
    public void updateOrders() throws Exception {
        TmsOrderCallHistoryExample example = new TmsOrderCallHistoryExample();
        example.setOrderByClause(" create_time DESC");
        example.createCriteria().andTmsUrlTypeEqualTo(20).andMessageCodeGreaterThan("200").andSuccessEqualTo(true);
        final String url = TmsUrlConstant.PULL_ORDER_HISTORY;
        List<TmsOrderCallHistory> list = tmsOrderCallHistoryMapper.selectByExample(example);
        LOGGER.info("===dtmsOrderCallHistoryMapper.selectByExample()==={}", example);
        if (CollectionUtils.isNotEmpty(list)) {
            for (TmsOrderCallHistory tmsOrderCallHistory : list) {
                Map<String, Object> paramsMap = new HashedMap<>();
                paramsMap.put("params", tmsOrderCallHistory.getParameters());
                Map<String, Object> resultMap = this.urlCall(url, paramsMap, 60000);
                String orderLineId = (String) resultMap.get("vcdriverno");
                String vccard = (String) resultMap.get("vccard");
                this.updateOrderByLineId(orderLineId, vccard, tmsOrderCallHistory.getId(), TmsUrlTypeEnum.PULL_ORDER_HISTORY.getValue());
            }
        }
    }


    /**
     * 关联用户与订单信息
     *
     * @param orderLineId
     * @param vccard
     * @param orderHistoryId
     * @param urlType
     */

    private void updateOrderByLineId(String orderLineId, String vccard, Long orderHistoryId, int urlType) throws Exception {
        String phone = this.getDUserExtService().selectByIdCard(vccard);
        DWaybill dWaybill = this.getdWaybillMapper().selectByPrimaryKey(Long.parseLong(orderLineId));
        if (null != dWaybill) {
            String waybillIdStr = dWaybill.getId().toString();
            String tmsSerialNo = dWaybill.getOrderLineId().toString();
            int lastStatus = dWaybill.getWaybillStatus().intValue();
            if (dWaybill.getUserId().longValue() > 0L) {
                LOGGER.info("===dispatchDriver===运单已派单给其他司机=={}", dWaybill.getUserId());
                this.tmsQueueService.removeOrder(waybillIdStr, tmsSerialNo);
                throw new BusinessException("此订单已指派给其他司机");
            }

            SUser user = this.getUserService().getByPhone(phone, Arrays.asList(new Integer[]{Integer.valueOf(UserTypeEnum.SEND_DRIVER.getValue())}));

            if (null == user) {
                LOGGER.info("===dispatchDriver===用户不可用=={}", phone);
                this.tmsQueueService.removeDriver(phone);
                throw new BusinessException("接单司机用户不可用");
            }

            dWaybill.setUserId(user.getId());
            dWaybill.setDispatchTime(new Date());
            dWaybill.setWaybillStatus(Integer.valueOf(DWaybillStatusEnum.DEPARTURE.getValue()));
            int count = this.getdWaybillMapper().updateByPrimaryKeySelective(dWaybill);
            //接口调用记录
            TmsOrderCallHistory callHistory = new TmsOrderCallHistory();
            if (count > 0) {
                callHistory.setIsUpdatehistory(true);
            } else {
                callHistory.setIsUpdatehistory(false);
            }
            callHistory.setTmsUrlType(urlType);
            callHistory.setId(orderHistoryId);
            tmsOrderCallHistoryMapper.insertSelective(callHistory);
            LOGGER.info("===tmsOrderCallHistoryMapper.updateByPrimaryKey=={}", callHistory);
            this.dWaybillStatusHistoryService.add(dWaybill.getId(), DWaybillStatusTypeEnum.PROCESS.getText(), DWaybillStatusEnum.DEPARTURE.getText(), DWaybillStatusEnum.getByValue(lastStatus).getText(), Long.valueOf(0L), "系统派单");

        }
    }


    /**
     * 推送消息到TMS
     *
     * @param url
     * @param paramsMap
     * @param socketTimeout
     * @return
     */
    private Map<String, Object> urlCall(final String url, final Map<String, Object> paramsMap, final int socketTimeout) {
        String result = HttpRequestUtil.sendHttpPost(url, paramsMap, socketTimeout);
        JSONObject jasonObject = JSONObject.parseObject(result);
        Map<String, Object> map = jasonObject;
        return map;
    }


}
